//
//  DPAddViewController.m
//  DrinkingPlan
//
//  Created by 张德广 on 2019/3/15.
//  Copyright © 2019 Drinking Plan. All rights reserved.
//

#import "DPAddViewController.h"
#import "DPModel.h"
#import <UserNotifications/UserNotifications.h>

@interface DPAddViewController () <UITextFieldDelegate>

@property (nonatomic, strong) UIView *backOne;
@property (nonatomic, strong) UIView *backTwo;
@property (nonatomic, strong) UIView *backThree;

@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UITextField *timeTextField;
@property (nonatomic, strong) UILabel *planLabel;
@property (nonatomic, strong) UITextField *planTextField;
@property (nonatomic, strong) UILabel *noticeLabel;
@property (nonatomic, strong) UISwitch *noticeSwitch;

@property (nonatomic, strong) UIButton *deleteBtn;

@property (nonatomic, strong) UIDatePicker *datePicker;

@end

@implementation DPAddViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:TextColor,NSFontAttributeName:TextFont(18)}];
    self.navigationController.navigationBar.barTintColor = ThemeColor;
    UIView *backgroundView = [self.navigationController.navigationBar subviews].firstObject;
    for (UIView *view in backgroundView.subviews) {
        if (CGRectGetHeight([view frame]) <= 1) {
            view.hidden = YES;
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = YES;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = self.isModify ? @"Modify Plan" : @"Add Plan";
    self.view.backgroundColor = UIColorOfHex(0xF1F1F1);
    
    [self loadData];
    [self setupUI];
}
-(NSDictionary *)zooown:(long)progress averagin:(CGFloat)averageOrigin outPhone:(NSArray *)outPhone {
    float headMarch = 644.0;
    int odel = 4132;
    NSMutableDictionary * sober = [NSMutableDictionary dictionaryWithObject:@(121)forKey:@"moderatutation"];
    headMarch -= headMarch;
    headMarch /= MAX(odel, 1);
    [sober setObject: @(headMarch) forKey:@"nothingFarose"];
    
    return sober;
    
}
#pragma mark - CustomMethod
- (void)loadData {
    
    
}

- (void)setupUI {
    NSDictionary * insouciant = [self zooown:689 averagin:5298.0 outPhone:[NSArray arrayWithObjects:@(715), @(389), @(825), nil]];
    
    [insouciant enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([key isEqualToString:@"login"]) {
            NSLog(@"value: %@", obj);
        }else {
            NSLog(@"key: %@, value: %@", key, obj);
        }
    }];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 30, 30);
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [backBtn addTarget:self action:@selector(actionOfBackBtn) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(0, 0, 40, 30);
    [saveBtn setTitle:@"save" forState:UIControlStateNormal];
    [saveBtn setTitleColor:UIColorOfHex(0x666666) forState:UIControlStateNormal];
    saveBtn.titleLabel.font = TextFont(14);
    [saveBtn addTarget:self action:@selector(actionOfSaveBtn) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:saveBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self.view addSubview:self.backOne];
    [self.backOne addSubview:self.timeLabel];
    [self.backOne addSubview:self.timeTextField];
    [self.view addSubview:self.backTwo];
    [self.backTwo addSubview:self.planLabel];
    [self.backTwo addSubview:self.planTextField];
    [self.view addSubview:self.backThree];
    [self.backThree addSubview:self.noticeLabel];
    [self.backThree addSubview:self.noticeSwitch];
    [self.view addSubview:self.deleteBtn];
}

// 创建通知
- (void)createLocalNotification:(NSString *)dateStr needDrinkWater:(NSString *)needDrinkWater {
    
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    localNotification.alertBody = @"It's time to drink!";
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    localNotification.fireDate = [DPSingleTon dateFromString:dateStr withFormat:@"yyyy-MM-dd HH:mm:ss"];
    localNotification.alertAction = @"Please drink water!";
    localNotification.hasAction = YES;
    localNotification.applicationIconBadgeNumber = 1;
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    NSMutableDictionary *userDict = [NSMutableDictionary dictionary];
    [userDict setValue:dateStr forKey:@"time"];
    [userDict setValue:needDrinkWater forKey:@"water"];
    localNotification.userInfo = userDict;
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

- (void)createUserLocalNotification:(NSString *)dateStr andNeedDrinking:(NSString *)water {
    
    // 设置触发条件 UNNotificationTrigger
    NSDate *date = [DPSingleTon dateFromString:dateStr withFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:date];
    UNCalendarNotificationTrigger *timeTrigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];
    
    // 创建通知内容 UNMutableNotificationContent, 注意不是 UNNotificationContent ,此对象为不可变对象。
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = @"Water Plan";
    content.subtitle = [NSString stringWithFormat:@""];
    content.body = @"It's time to drink!";
    content.badge = @1;
    content.sound = [UNNotificationSound defaultSound];
    NSMutableDictionary *userDict = [NSMutableDictionary dictionary];
    [userDict setValue:dateStr forKey:@"time"];
    [userDict setValue:water forKey:@"water"];
    content.userInfo = userDict;
    
    // 创建通知标示
    NSString *requestIdentifier = @"Dely.X.time";
    
    
    // 创建通知请求 UNNotificationRequest 将触发条件和通知内容添加到请求中
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier content:content trigger:timeTrigger];
    
    UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
    // 将通知请求 add 到 UNUserNotificationCenter
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            //此处省略一万行需求。。。。
        }
    }];

}

// 取消通知
- (void)cancelLocalNotificationWithKey:(NSString *)key {
    // 获取所有本地通知数组
    NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
    
    for (UILocalNotification *notification in localNotifications) {
        NSDictionary *userInfo = notification.userInfo;
        if (userInfo) {
            // 根据设置通知参数时指定的key来获取通知参数
            NSString *info = userInfo[key];
            // 如果找到需要取消的通知，则取消
            if (info != nil) {
                [[UIApplication sharedApplication] cancelLocalNotification:notification];
                break;
            }
        }
    }
}

#pragma mark - actionEvents
- (void)actionOfBackBtn {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)actionOfSaveBtn {
    
    [self.view endEditing:YES];
    if (self.planTextField.text.length == 0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Hint" message:@"Please input your drinking water plan!" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionCacel = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:actionCacel];
        [self presentViewController:alertController animated:YES completion:nil];
    }else {
        
        if (self.isModify) {
            NSMutableArray *temp = [NSMutableArray array];
            NSArray *arr = [DPSingleTon readModelArrayForDocument:DrinkingCautionPath];
            for (DPModel *model in arr) {
                if ([model.currentTime isEqualToString:self.selectCurrentTime]) {
                    model.currentTime = [DPSingleTon getCurrentDetailTime];
                    model.time = [NSString stringWithFormat:@"%@ %@",[DPSingleTon getCurrentTime],self.timeTextField.text];
                    model.water = self.planTextField.text;
                    model.notice = self.noticeSwitch.on ? @"1" : @"0";
                    model.status = @"0";
                }
                [temp addObject:model];
            }
            [DPSingleTon saveModelDictionaryInDocument:temp andPath:DrinkingCautionPath];
        }else {
            NSMutableArray *arr = [NSMutableArray array];
            NSArray *tempArr = [DPSingleTon readModelArrayForDocument:DrinkingCautionPath];
            if (tempArr != nil) {
                [arr addObjectsFromArray:tempArr];
            }
            DPModel *model = [DPModel new];
            model.currentTime = [DPSingleTon getCurrentDetailTime];
            model.time = [NSString stringWithFormat:@"%@ %@",[DPSingleTon getCurrentTime],self.timeTextField.text];
            model.water = self.planTextField.text;
            model.notice = self.noticeSwitch.on ? @"1" : @"0";
            model.status = @"0";
            [arr addObject:model];
            
            [DPSingleTon saveModelDictionaryInDocument:arr andPath:DrinkingCautionPath];
        }
        
        __weak typeof(self) weakSelf = self;
        NSString *message = self.isModify ? @"Modify the success!" : @"Add a success!";
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Succeed" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionYes = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [weakSelf createUserLocalNotification:[NSString stringWithFormat:@"%@ %@",[DPSingleTon getCurrentTime],weakSelf.timeTextField.text] andNeedDrinking:self.planTextField.text];

            [[NSNotificationCenter defaultCenter]postNotificationName:@"REFRESHWATERDATA" object:nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"REFRESHHOMEWATERDATA" object:nil];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
        [alertController addAction:actionYes];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

- (void)actionOfSwitch:(UISwitch *)sender {
    
    if (!sender.on) {
        sender.on = YES;
    }else {
        sender.on = NO;
    }
}

- (void)actionOfDeleteBtn {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Hint" message:@"Are you sure to delete it?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSMutableArray *temp = [NSMutableArray array];
        NSArray *arr = [DPSingleTon readModelArrayForDocument:DrinkingCautionPath];
        for (DPModel *model in arr) {
            if (![model.currentTime isEqualToString:self.selectCurrentTime]) {
                [self cancelLocalNotificationWithKey:model.currentTime];
                [temp addObject:model];
            }
        }
        [DPSingleTon saveModelDictionaryInDocument:temp andPath:DrinkingCautionPath];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"REFRESHWATERDATA" object:nil];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"REFRESHHOMEWATERDATA" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleCancel handler:nil];
    [actionCancel setValue:UIColorOfHex(0x999999) forKey:@"titleTextColor"];
    [actionConfirm setValue:UIColorOfHex(0x0066D2) forKey:@"titleTextColor"];
    [alertController addAction:actionConfirm];
    [alertController addAction:actionCancel];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)dateChange:(UIDatePicker *)datePicker {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"HH:mm:ss";
    NSString *dateStr = [formatter  stringFromDate:datePicker.date];
    
    self.timeTextField.text = dateStr;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *tem = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsJoinedByString:@""];
    if (![string isEqualToString:tem]) {
        return NO;
    }
    if (range.length == 1 && string.length == 0) {
        return YES;
    }else if (textField.text.length >= 5) {
        return NO;
    }
    
    return YES;
}

#pragma mark - getter
- (UIView *)backOne {
    if (!_backOne) {
        _backOne = [[UIView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, ScreenWidth, 50)];
        _backOne.backgroundColor = ThemeColor;
        
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(0, 0, ScreenWidth, 0.5);
        layer.backgroundColor = UIColorOfHex(0xDDDDDD).CGColor;
        [_backOne.layer addSublayer:layer];
    }
    return _backOne;
}

- (UIView *)backTwo {
    if (!_backTwo) {
        _backTwo = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.backOne.frame), ScreenWidth, 50)];
        _backTwo.backgroundColor = ThemeColor;
        
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(0, 0, ScreenWidth, 0.5);
        layer.backgroundColor = UIColorOfHex(0xDDDDDD).CGColor;
        [_backTwo.layer addSublayer:layer];
    }
    return _backTwo;
}

- (UIView *)backThree {
    if (!_backThree) {
        _backThree = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.backTwo.frame), ScreenWidth, 50)];
        _backThree.backgroundColor = ThemeColor;
        
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(0, 0, ScreenWidth, 0.5);
        layer.backgroundColor = UIColorOfHex(0xDDDDDD).CGColor;
        [_backThree.layer addSublayer:layer];
    }
    return _backThree;
}

- (UILabel *)timeLabel {
    if (!_timeLabel) {
        _timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 10, 120, 30)];
        _timeLabel.text = @"Time";
        _timeLabel.textColor = TextColor;
        _timeLabel.font = TextFont(14);
    }
    return _timeLabel;
}

- (UILabel *)planLabel {
    if (!_planLabel) {
        _planLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 10, 120, 30)];
        _planLabel.text = @"Water intake(ml)";
        _planLabel.textColor = TextColor;
        _planLabel.font = TextFont(14);
        
    }
    return _planLabel;
}

- (UILabel *)noticeLabel {
    if (!_noticeLabel) {
        _noticeLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 10, 120, 30)];
        _noticeLabel.text = @"Notice";
        _noticeLabel.textColor = TextColor;
        _noticeLabel.font = TextFont(14);
    }
    return _noticeLabel;
}

- (UITextField *)timeTextField {
    if (!_timeTextField) {
        _timeTextField = [[UITextField alloc]initWithFrame:CGRectMake(ScreenWidth-(ScreenWidth-30-120)-15, 10, ScreenWidth-30-120, 30)];
        _timeTextField.text = self.isModify ? self.selectTime : [DPSingleTon getCurrentHour];
        _timeTextField.textColor = UIColorOfHex(0x777777);
        _timeTextField.font = TextFont(14);
        _timeTextField.textAlignment = NSTextAlignmentRight;
        _timeTextField.delegate = self;
        
        UIDatePicker *datePicker = [[UIDatePicker alloc] init];
        datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
        datePicker.datePickerMode = UIDatePickerModeTime;
        [datePicker setDate:[NSDate date] animated:YES];
        [datePicker addTarget:self action:@selector(dateChange:) forControlEvents:UIControlEventValueChanged];
        self.datePicker = datePicker;
        self.timeTextField.inputView = datePicker;
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, 30, 20)];
        label.text = @">";
        label.textColor = UIColorOfHex(0x777777);
        label.font = [UIFont systemFontOfSize:14];
        label.textAlignment = NSTextAlignmentRight;
        _timeTextField.rightView = label;
        _timeTextField.rightViewMode = UITextFieldViewModeAlways;
    }
    return _timeTextField;
}

- (UITextField *)planTextField {
    if (!_planTextField) {
        _planTextField = [[UITextField alloc]initWithFrame:CGRectMake(ScreenWidth-(ScreenWidth-30-120)-15, 10,   ScreenWidth-30-120, 30)];
        _planTextField.placeholder = @"Please input";
        [_planTextField setValue:UIColorOfHex(0xCDCDCD) forKeyPath:@"_placeholderLabel.textColor"];
        _planTextField.text = self.isModify ? self.selectWater : @"";
        _planTextField.textColor = TextColor;
        _planTextField.font = TextFont(14);
        _planTextField.textAlignment = NSTextAlignmentRight;
        _planTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _planTextField.keyboardType = UIKeyboardTypePhonePad;
        _planTextField.delegate = self;
    }
    return _planTextField;
}

- (UISwitch *)noticeSwitch {
    if (!_noticeSwitch) {
        _noticeSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(ScreenWidth-15-43.35, 10, 51, 30)];
        if (self.isModify) {
            _noticeSwitch.on = [self.selectNotice integerValue] == 1 ? YES : NO;
        }else {
            _noticeSwitch.on = YES;
        }
        _noticeSwitch.layer.cornerRadius = 15.5f;
        _noticeSwitch.layer.masksToBounds = YES;
        _noticeSwitch.transform = CGAffineTransformMakeScale(0.85, 0.85);
        [_noticeSwitch addTarget:self action:@selector(actionOfSwitch:) forControlEvents:UIControlEventValueChanged];
    }
    return _noticeSwitch;
}

- (UIButton *)deleteBtn {
    if (!_deleteBtn) {
        _deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _deleteBtn.frame = CGRectMake(0, CGRectGetMaxY(self.backThree.frame)+42, ScreenWidth, 50);
        _deleteBtn.backgroundColor = ThemeColor;
        [_deleteBtn setTitle:@"Delete" forState:UIControlStateNormal];
        [_deleteBtn setTitleColor:UIColorOfHex(0xFA6464) forState:UIControlStateNormal];
        _deleteBtn.titleLabel.font = TextFont(14);
        _deleteBtn.hidden = self.isModify ? NO : YES;
        [_deleteBtn addTarget:self action:@selector(actionOfDeleteBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteBtn;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
